﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using APA_DAO;
using TAM_SPORT;
using System.Text.RegularExpressions;

namespace AMS
{
    public partial class FrmPhong : Form
    {
        private int myRoomID = 0;
        public FrmPhong()
        {
            InitializeComponent();
            cbxStatus.SelectedIndex = 0;
            loadGrid();
            dgdPhong.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSkyBlue;
            dgdPhong.GridColor = Color.BurlyWood;
            dgdPhong.EnableHeadersVisualStyles = false;
            this.BackColor = Color.LightCyan;
        }
        
        private void btnCapture_Click(object sender, EventArgs e)
        {

        }

        private void btnBrows_Click(object sender, EventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }


        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtMaCanHo_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {          
            //bool validation = false;
            bool validation = true;
            string sphong = txtSoPhong.Text;
            string dongia = txtDonGia.Text;
            string dtich = txtDienTich.Text;

            if (string.IsNullOrEmpty(sphong) 
                || string.IsNullOrEmpty(dongia) || !Regex.IsMatch(dongia.Replace(",", ""), "^[0-9]+(\\.[0-9]+)?$")
                || string.IsNullOrEmpty(dtich) || !Regex.IsMatch(dtich.Replace(",", ""), "^[0-9]+(\\.[0-9]+)?$"))
            {
                validation = false;
            }
            StringBuilder strErr = new StringBuilder();
            int i = 0;
            if (string.IsNullOrEmpty(sphong))
            {
                i++;
                strErr.Append(i + ". Chưa nhập số phòng.");
                validation = false;
            }
            else if (this.myRoomID == 0 && checkRoomIsAvailable(sphong))
            {
                i++;
                strErr.Append(i + ". Phòng này đã có.");
                validation = false;
            }
            if (string.IsNullOrEmpty(dongia) || !Regex.IsMatch(dongia.Replace(",", ""), "^[0-9]+(\\.[0-9]+)?$"))
            {
                i++;
                if (!validation)
                {
                    strErr.Append("\n");
                }
                strErr.Append(i + ". Chưa nhập đơn giá hoặc đơn giá không đúng định dạng.");
                validation = false;
            }

            if (string.IsNullOrEmpty(dtich) || !Regex.IsMatch(dtich.Replace(",",""), "^[0-9]+(\\.[0-9]+)?$"))
            {
                i++;
                if (!validation)
                {
                    strErr.Append("\n");
                }
                strErr.Append(i + ". Chưa nhập diện tích hoặc diện tích không đúng định dạng.");
                validation = false;
            }

            //validation
            if (validation == false)
            {
                Error err = new Error(strErr.ToString());
                err.ShowDialog();
                err.Dispose();
            }
            else
            {
                PhongDao dao = new PhongDao();
                bool success = false;
                if (this.myRoomID > 0)
                {// update 
                    success = dao.upadtePhong(sphong.Trim(), dongia.Trim(), dtich.Trim(), rtbGhiChu.Text, this.myRoomID);
                } 
                else
                { // insert
                    success = dao.insertPhong(sphong.Trim(), dongia.Trim(), dtich.Trim(),  rtbGhiChu.Text);
                }

                if (success)
                {
                    Result f = new Result("Lưu thành công!");
                    f.ShowDialog();
                    f.Dispose();
                    this.myRoomID = 0;
                }
                else
                {
                    Error err = new Error("Lưu thất bại.");
                    err.ShowDialog();
                    err.Dispose();
                }
                if(success)
                {
                    loadGrid();
                    clearAll();
                }
            }
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void loadGrid()
        {
            dgdPhong.Rows.Clear();
            PhongDao dao = new PhongDao();
            DataTable table = dao.getPhongs(txtSoPhongSearch.Text.ToString(), cbxStatus.SelectedIndex);
            int i = 0;
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    i = dgdPhong.Rows.Add();
                    dgdPhong.Rows[i].Cells[0].Value = (i+1).ToString();
                    dgdPhong.Rows[i].Cells[1].Value = row["ID"].ToString();                    
                    dgdPhong.Rows[i].Cells[2].Value = row["SO_PHONG"].ToString();
                    dgdPhong.Rows[i].Cells[3].Value = float.Parse(row["DON_GIA"].ToString()).ToString("#,###,##.##");
                    dgdPhong.Rows[i].Cells[4].Value = float.Parse(row["DIEN_TICH"].ToString()).ToString("#,###,##.##");
                    dgdPhong.Rows[i].Cells[5].Value = int.Parse(row["TINH_TRANG"].ToString()) == 2 ? "Đã thuê" : "Còn trống";
                    dgdPhong.Rows[i].Cells[6].Value = row["GHI_CHU"].ToString();
                    dgdPhong.Rows[i].Cells[7].Value = row["TINH_TRANG"].ToString();
                    if (int.Parse(row["TINH_TRANG"].ToString()) == 2)
                    {
                        dgdPhong.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    }                    
                }
            }
        }
        private void btnAdd_Click_1(object sender, EventArgs e)
        {

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            loadGrid();
        }

        private void dgdPhong_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void dgdPhong_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex >= 0)
            {
                if(e.ColumnIndex == 8)
                {
                    // edit
                    this.myRoomID = int.Parse(dgdPhong.Rows[e.RowIndex].Cells[1].Value.ToString());
                    txtSoPhong.Text = (String)dgdPhong.Rows[e.RowIndex].Cells[2].Value;
                    txtDonGia.Text = ((String)dgdPhong.Rows[e.RowIndex].Cells[3].Value).Replace(",","");
                    txtDienTich.Text = ((String)dgdPhong.Rows[e.RowIndex].Cells[4].Value).Replace(",", "");
                    rtbGhiChu.Text =  (String)dgdPhong.Rows[e.RowIndex].Cells[6].Value;
                    bool dathue = ((String)dgdPhong.Rows[e.RowIndex].Cells[5].Value).Equals("Đã thuê");
                } 
                else if(e.ColumnIndex == 9)
                {
                    // delete 
                    bool dathue = ((String)dgdPhong.Rows[e.RowIndex].Cells[5].Value).Equals("Đã thuê");
                    if(dathue)
                    {
                        Error er = new Error("Phòng này đã được thuê. Bạn không thể xóa!");
                        er.ShowDialog();
                        er.Dispose();
                        return;
                    }
                    Confirm confirm = new Confirm("Bạn có muốn xóa phòng số : " + (String)dgdPhong.Rows[e.RowIndex].Cells[2].Value);
                    confirm.ShowDialog();
                    if (confirm.IsAccept)
                    {
                        int phongID = int.Parse((String)dgdPhong.Rows[e.RowIndex].Cells[1].Value);
                        PhongDao dao = new PhongDao();
                        if (dao.deletePhong(phongID))
                        {
                            Result re = new Result("Xóa thành công.");
                            re.ShowDialog();
                            re.Dispose();
                            loadGrid();
                        }
                        else
                        {
                            Error er = new Error("Xóa thất bại.");
                            er.ShowDialog();
                            er.Dispose();
                        }
                       
                    }
                    confirm.Dispose();
                }
            }
        }

        private void dgdPhong_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 2)
            {
                int id = int.Parse(dgdPhong.Rows[e.RowIndex].Cells[1].Value.ToString());
                int status = int.Parse(dgdPhong.Rows[e.RowIndex].Cells[7].Value.ToString());
                if (status == 1)
                {
                    FrmThuePhong f = new FrmThuePhong(id);
                    f.MdiParent = this.MdiParent;
                    f.Show();
                }
                else
                {
                    Error er = new Error("Phòng này đã được thuê.");
                    er.ShowDialog();
                    er.Dispose();
                }
            }
        }

        private void clearAll()
        {
            this.myRoomID = 0;
            txtDienTich.Text = "";
            txtDonGia.Text = "";
            txtSoPhong.Text = "";
            rtbGhiChu.Text = "";
            txtSoPhong.ReadOnly = false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.myRoomID = 0;
            txtDienTich.Text = "";
            txtDonGia.Text = "";
            txtSoPhong.Text = "";
            rtbGhiChu.Text = "";
            txtSoPhong.ReadOnly = false;
        }

        private String RemoveComma(String value)
        {
            if (value != null && value.Contains(","))
            {
                value = value.Replace(",", String.Empty).Trim();
            }
            return value;
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            if (RemoveComma(txtDonGia.Text).Length > 3)
            {
                txtDonGia.Text = decimal.Parse(RemoveComma(txtDonGia.Text)).ToString("#,###");
                txtDonGia.Select(txtDonGia.Text.Length, 0);
            }
        }

        private void txtDonGia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtDienTich_TextChanged(object sender, EventArgs e)
        {
            if (RemoveComma(txtDienTich.Text).Length > 3)
            {
                txtDienTich.Text = decimal.Parse(RemoveComma(txtDienTich.Text)).ToString("#,###");
                txtDienTich.Select(txtDienTich.Text.Length, 0);
            }
        }

        private void txtDienTich_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private bool checkRoomIsAvailable(string sphong)
        {
            int rowCount = dgdPhong.RowCount;
            for(int idx = 0; idx < rowCount ; idx++)
            {
                string room = (String)dgdPhong.Rows[idx].Cells[2].Value;
                if(sphong.ToLower().Equals(room.ToLower()))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
